#!/bin/bash
#
# Module that implements platform checking and handling.
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 18 November 2013
#
#   Copyright 2012-2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#


## p_platform_find
##
## Determines the currently executing system platform by running the
## platform scoring functions for each supported platform. The highest-scoring
## platform is the selected platform, provided that the platform score is
## at least 60. If two platforms have the same score, the platform that is
## scored second will be the selected platform among the two. The platform
## defaults to "unknown" if no platform matches.
##
## Echoes the match result in platform=score format. Returns 0 on success,
## non-zero if an error occurs during the platform detection process.
##
function p_platform_find() {
	local platname=unknown
	local selplat=unknown
	local -i score=0
	local -i highscore=0
	local -i status=0
	
	for plat in $(ls "${P_LIBDIR}/platforms"/*.platform); do
		. "${plat}"
		platname=$(p_platform_score)
		status=$(merge_status ${status} $?)
		
		score=$(echo "${platname}" | sed 's/.*=//')
		
		if ((score >= 60 && score >= highscore)); then
			selplat=$(echo "${platname}" | sed 's/=.*//')
			highscore=${score}
		fi
	done
	
	echo "${selplat}"
	return ${status}
}


## p_platform_init_context <platform name>
##
## Initializes general and platform-specific context information for Pulley.
## Returns 0 on success, non-zero on failure.
##
function p_platform_init_context() {
	local status=0
	
	# Write the Pulley version to the root of the pulley/ tree
	set_context pulley "${PULLEY_VERSION}"
	status=$?
	
	. "${P_LIBDIR}/platforms/$1.platform"
	
	# Run platform handler
	p_platform_set_context
	status=$(merge_status ${status} $?)
	
	# Clean up
	unset -f p_platform_score
	unset -f p_platform_set_context
	
	return ${status}
}


## p_platform_detect
##
## Determines the platform on which Pulley is running and sets the appropriate
## initial context information. Returns 0 if successful, non-zero if an
## error occurs.
##
function p_platform_detect() {
	local platform=
	local status=0
	
	platform=$(p_platform_find)
	status=$?
	
	if ((status == 0)); then
		p_platform_init_context "${platform}"
		status=$?
	fi
	
	return ${status}
}
